package com.example.volleytest.network;

import android.graphics.Bitmap;
import android.os.Build;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader;

public class ComplexCache implements ImageLoader.ImageCache {
    private LruCache<String, Bitmap> memoryCache;

    public ComplexCache(float memCachePercent) {
        int memCacheSize = Math.round(memCachePercent * Runtime.getRuntime().maxMemory() / 1024);
        memoryCache = new LruCache<String, Bitmap>(memCacheSize) {
            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, Bitmap value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {
        return memoryCache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        memoryCache.put(url, bitmap);
    }

    public static int getBitmapSize(Bitmap bitmap) {
        if (hasHoneycombMR1()) {
            return bitmap.getByteCount();
        }

        // Pre HC-MR1
        return bitmap.getRowBytes() * bitmap.getHeight();
    }

    public static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
    }

}
